export const state = () => ({
    signIn: true,
    account: "test"
})

export const mutations = {
    setSignIn(state, signIn) {
        state.signIn = signIn
    },
    setAccount(state, account) {
        state.account = account
    }
}

export const actions = {
    getAccountList({}) {
        return this.$api.account.getAccountList().then((res) => {
            if(res.data.code==200){
                return Promise.resolve(res.data.data)
            }
            else{
                this.$router.push("/mainPage/error")
                return Promise.reject(new Error(res.data.msg))
            }
        },(error) => {
            this.$router.push("/mainPage/error")
            return Promise.reject(error)
        }).catch((error)=>{
            this.$router.push("/mainPage/error")
            return Promise.reject(error)
        })
    },
    updateAccount({},{nick_name,dormitory,phone,password}){
        return this.$api.account.updateAccount(nick_name,dormitory,phone,password).then((res)=>{
            if(res.data.code==200){
                return Promise.resolve(res.data.msg)
            }
            else{
                this.$router.push("/mainPage/error")
                return Promise.reject(new Error(res.data.msg))
            }
        },(error) => {
            this.$router.push("/mainPage/error")
            return Promise.reject(error)
        }).catch((error)=>{
            this.$router.push("/mainPage/error")
            return Promise.reject(error)
        })
    },
    signOut({commit}) {
        commit('setSignIn', false)
        commit('setAccount', null)
        localStorage.removeItem('account')
    },
    signIn({commit},{userName, password}){
        return this.$api.account.getAccount('getAccountByUsernameAndPassword', userName, password).then((res) => {
            if(res.data.status === 'OK' && res.data.msg === 'admin') {
                commit('setSignIn',true)
                commit('setAccount',res.data.data)
                localStorage.setItem('account', JSON.stringify(res.data.data))
                return Promise.resolve('OK')
            }
            else
            {
                return Promise.reject(new Error("请输入正确的管理员账号与密码!"))
            }
        },(error)=>{
            return Promise.reject(error)
        }).catch((error)=>{
            return Promise.reject(error)
        })
    }
}
